package com.sinosoft.vaccinetoai.security.shiro.filter;

import cn.hutool.json.JSONUtil;
import com.sinosoft.vaccinetoai.common.ApiResult;
import com.sinosoft.vaccinetoai.exception.ExceptionEnums;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义身份认证拦截器
 * @author xzh
 * @date 2022-10-24 11:04
 * @since 1.0.0
 */
public class CustomAuthenticationFilter extends AuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_OK);
        res.setCharacterEncoding("UTF-8");
        try {
            PrintWriter writer = res.getWriter();
            writer.write(JSONUtil.toJsonStr(ApiResult.ofExceptionEnums(ExceptionEnums.LOGIN_STATE_INVALID)));
            writer.close();
        } catch (Exception e) {

        }
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if(request instanceof HttpServletRequest) {
            if("OPTIONS".equals(((HttpServletRequest) request).getMethod().toUpperCase())) {
                return true;
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

}
